<?php

namespace app\admin\controller\user;

use app\admin\model\Category;
use app\admin\model\District;
use app\admin\model\Expertise;
use app\admin\model\Skill;
use app\api\model\Userbank;
use app\common\controller\Backend;
use think\Db;
use app\admin\model\User as AdminUser;
use app\admin\model\Category as AdminCategoryModel;
use app\admin\model\Levels;
use think\Log;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;


    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
                $list[$k]['work_status_name'] = AdminUser::getWorkStausName($list[$k]['state']);
                $levelsName = '';
                if ($v['livels_id']) {
                    $levels = Levels::findInfoByCondition(['id' => $v['livels_id']]);
                    $levelsName = $levels ? $levels['livels'] : '';
                }
                $list[$k]['levels_name'] = $levelsName;

                $categoryName = '';
                if ($v['category_id']) {
                    $category = Category::findInfoByCondition(['id' => $v['category_id']]);
                    $categoryName = $category ? $category['name'] : '';
                }
                $list[$k]['category_name'] = $categoryName;

                // 擅长领域
                $expertiseName = '';
                if ($v['expertise']) {
                    $expertise = Expertise::findListByCondition(['id' => ['in', explode(',', $v['expertise'])]]);
                    if ($expertise) {
                        foreach ($expertise as $expertiseVal) {
                            $expertiseName .= (',' . $expertiseVal['name']);
                        }
                        $expertiseName = trim($expertiseName, ',');
                    }
                }
                $list[$k]['expertise_name'] = $expertiseName;
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));

        //return parent::edit($ids);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (isset($params['expertise']) && $params['expertise'] && is_array($params['expertise'])) {
                        $params['expertise'] = implode(',', $params['expertise']);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $row['verification_status_name'] = $row['verification_status'] == 1 ? '已认证' : '未认证';

        //获取职位列表
        $list = AdminCategoryModel::findListByCondition(['type' => 'default', 'pid' => ['gt', 0]]);
        $listData = [];
        if ($list) {
            foreach ($list as $listVal) {
                $listData[$listVal['id']] = $listVal['name'];
            }
        }
        $listData[0] = '请选择';
        $this->assign('categorydata', $listData);

        //获取职级列表
        $levels = Levels::findListByCondition();
        $levelsData = [];
        if ($levels) {
            foreach ($levels as $listVal) {
                $levelsData[$listVal['id']] = $listVal['livels'];
            }
        }
        $levelsData[0] = '请选择';
        $this->assign('levels', $levelsData);

        // 获取省份
        $provinces = District::findListByCondition(['pid' => 1]);
        $provincesData = [];
        if ($provinces) {
            foreach ($provinces as $listVal) {
                $provincesData[$listVal['id']] = $listVal['district_name'];
            }
        }
        $provincesData[0] = '请选择';
        $this->assign('provinces', $provincesData);

        $city[0] = '请选择';
        $this->assign('city', $city);

        $district[0] = '请选择';
        $this->assign('district', $district);

        //获取技能标签
        $skill = Skill::findInfoByCondition(['user_id' => $row['id']]);
        $this->view->assign("skill", $skill);

        //领域
        $list = Expertise::findListByCondition();
        $levelsData = [];
        $levelsData[0] = '请选择';
        if ($levels) {
            foreach ($list as $listVal) {
                $levelsData[$listVal['id']] = $listVal['name'];
            }
        }
        $this->assign('expertise', $levelsData);

        //擅长领域
        $row['expertise'] = $row['expertise'] ? explode(',', $row['expertise']) : [];

        //获取用户的默认的银行信息
        $defaultBank = Userbank::findInfoByCondition(['user_id' => $row['id'], 'is_default' => 1]);
        if ($defaultBank) {
            $row['bank_username'] = $defaultBank['bank_name'];
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     *  分配的人才列表
     */
    public function categoryUsers()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            /*$total = $this->model
                ->with('user_category')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('user_category')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();*/

            $filter = $this->request->param('filter');
            if ($filter) {
                $filter =  json_decode(htmlspecialchars_decode($filter), TRUE);
            } else {
                $filter = [];
            }

            $total = AdminUser::assignUsersCount($filter);
            $list = AdminUser::assignUsers($filter, $sort, $order, $offset, $limit);
            //echo Db::getLastSql();exit;
            foreach ($list as $k => &$v) {
                unset($v['password']);
                unset($v['salt']);
                //获取职业岗位
                $category = Category::findInfoByCondition(['id' => $v['category_id']]);
                $v['category_name'] = $category ? $category['name'] : '';
                $v['createtime'] = $v['createtime'] ? date('Y-m-d H:i:s', $v['createtime']) : '';

                // 获取职业技能
                $skill = Skill::findInfoByCondition(['user_id' => $v['id']]);
                $v['skill'] = $skill ? $skill['skillstr'] : '';

                //工作状态
                if ($v['assign_uid'] > 0) {
                    if (in_array($v['work_status'], [0, 1])) {
                        $v['work_status_name'] = '工作中';
                    } elseif ($v['work_status'] == 2) {
                        $v['work_status_name'] = '已结束';
                    } elseif ($v['work_status'] == 3)  {
                        $v['work_status_name'] = '已退出';
                    } else  {
                        $v['work_status_name'] = '空闲中';
                    }
                } else {
                    $v['work_status_name'] = '空闲中';
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();

                    //删除相关的关联表
                    if ($v['id']) {
                        Db::name('user_token')->where(['user_id' => $v['id']])->delete();
                        Db::name('third')->where(['user_id' => $v['id']])->delete();
                    }
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
